//
//  PTMineVC.m
//  PotentialTraining
//
//  Created by admin on 2018/1/27.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "PTMineVC.h"
#import "MainInfoCell.h"
#import "mainClassCell.h"
#import "RankingView.h"
#import "InfoView.h"
#import "TZImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZLocationManager.h"
#import "TZImageManager.h"
#import "PTLoginVC.h"
#import "PTPromoteView.h"
#import "PTAddressView.h"
@interface PTMineVC ()<UITableViewDelegate,UITableViewDataSource,TableviewDidSelect,DidEditHeadImg,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
{
    //记录右侧选中的
    NSInteger secetRow;
}
@property (nonatomic, strong)UITableView *mainTab;
@property (nonatomic, strong) NSMutableArray *classAry;
/** 个人资料的View */
@property (nonatomic, strong) InfoView *infoView;
/** 排行榜的View */
@property (nonatomic, strong) RankingView *leftView;
/** 推广码View*/
@property (nonatomic, strong) PTPromoteView *promoteView;
/** 个人成绩数组 */
@property (nonatomic, strong) NSMutableArray *resultsAry;
/** 排行榜数组 */
@property (nonatomic, strong) NSMutableArray *rankAry;

/** 地址数组 */
@property (nonatomic, strong) NSArray *addressAry;

@end

@implementation PTMineVC

- (void) viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.infoView.addressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 500);
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self loadUserData];
}

- (void)loadUserData{
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:kUserFilePath];
    NSString *getUrl = [NSString stringWithFormat:@"%@%@user_id/%@", [[VersionManager shareManager] currentVersion], kGETINFO, userDic[@"user_id"]];
    kDLog(@"获取信息页面接口是：%@", getUrl);
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        NSDictionary *dic = result[@"data"];
        NSString *code = result[@"code"];
        NSLog(@"获取信息页面返回的信息是：%@", result);
        [self.infoView configWithData:dic];
        if ([code isEqualToString:@"11"] && dic != nil) {
            NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [mutDic setObject:@"暂无" forKey:@"label_id"];
            [mutDic writeToFile:kInfoFilePath atomically:YES];
            [self.mainTab reloadData];
        }
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取信息页失败，错误是：%@", error);
    }];
}

// http://47.94.254.145/qnxl/index.php/api10/user/getinfo/user_id/0000000002
// http://47.94.254.145/qnxl/index.php/Api10/user/getinfo/user_id/0000000002

- (NSMutableArray *)classAry{
    if (_classAry == nil) {
        _classAry = [NSMutableArray arrayWithObjects:@"排行榜",@"成绩查询",@"我的积分",@"我的推广码", nil];
    }
    return _classAry;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    secetRow = 0;
    [self addSubViews];
    
}

#pragma mark - 右侧视图
- (void) addSubViews{
    /*
     *
     *tabelview
     *
     */
    self.mainTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 300, kScreenHeight-49-64)];
    self.mainTab.backgroundColor = kColor(238, 238, 238);
    self.mainTab.delegate = self;
    self.mainTab.dataSource = self;
    self.mainTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTab.tableFooterView = [UIView new];
    [self.mainTab registerNib:[UINib nibWithNibName:NSStringFromClass([MainInfoCell class]) bundle:nil] forCellReuseIdentifier:@"MainInfoCell"];
    [self.mainTab registerNib:[UINib nibWithNibName:NSStringFromClass([mainClassCell class]) bundle:nil] forCellReuseIdentifier:@"mainClassCell"];
    [self.view addSubview:self.mainTab];
    self.infoView = [[InfoView alloc]initWithFrame:CGRectMake(300, 0, kScreenWidth - 300, kScreenHeight-49-64)];
    self.infoView.HeadImgDetegate = self;
    [self.view addSubview:self.infoView];
    self.infoView.hidden = NO;
    self.leftView = [[RankingView alloc]initWithFrame:CGRectMake(300, 0, kScreenWidth - 300, kScreenHeight-49-64)];
    self.leftView.TabDetegate = self;
    [self.view addSubview:self.leftView];
    self.leftView.hidden = YES;
    NSDictionary *userInfoDic = [NSDictionary dictionaryWithContentsOfFile:kInfoFilePath];
    self.infoView.dataDic = userInfoDic;
    [self.infoView configWithImgage:userInfoDic[@"icon_path"]];
    
    self.promoteView = [[PTPromoteView alloc]initWithFrame:CGRectMake(300+(kScreenWidth - 300)/2-200, (kScreenHeight-64)/2-100-40, 400, 200)];
    self.promoteView.hidden = YES;
    [self.view addSubview:self.promoteView];
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:kUserFilePath];
    [self.promoteView configWithPromoteStr:userDic[@"promocode"]];
}

#pragma mark - 第二列表的点击事件
- (void)DidselectTTab:(NSIndexPath *)indexPath{
    NSLog(@"%ld----%ld",indexPath.section,indexPath.row);
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        MainInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainInfoCell"];
        cell.backgroundColor = kColor(238, 238, 238);
        if (secetRow == 0) {
            cell.backgroundColor = kColor(254, 211, 54);
        }
        NSDictionary *userInfoDic = [NSDictionary dictionaryWithContentsOfFile:kInfoFilePath];
        [cell configWithData:userInfoDic];
        return cell;
    } else{
        mainClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mainClassCell"];
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.classAry[indexPath.row-1]];
        if (indexPath.row == 3) {
            cell.subLabel.hidden = NO;
        }else{
            cell.subLabel.hidden = YES;
        }
        if (secetRow == indexPath.row) {
            cell.backgroundColor = kColor(254, 211, 54);
        }else{
            cell.backgroundColor = kColor(238, 238, 238);
        }
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消点击后变色
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    secetRow = indexPath.row;
    [self.mainTab reloadData];
    if (indexPath.row == 0) {
        self.infoView.hidden = NO;
        self.leftView.hidden = YES;
        self.promoteView.hidden = YES;
    }else if (indexPath.row == 1 ){
        [self getRankScoreInfo]; // 排行榜
        self.leftView.hidden = NO;
        self.infoView.hidden = YES;
        self.promoteView.hidden = YES;
    }else if (indexPath.row == 2){
        [self getPersonalScoreInfo]; // 个人成绩
        self.leftView.hidden = NO;
        self.infoView.hidden = YES;
        self.promoteView.hidden = YES;
    }else if (indexPath.row == 3){  // 我的积分
        self.leftView.hidden = YES;
        self.infoView.hidden = YES;
        self.promoteView.hidden = YES;
    }else{  //我的推广码
        self.leftView.hidden = YES;
        self.infoView.hidden = YES;
        self.promoteView.hidden = NO;
    }
    
    if (indexPath.row != 0) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.infoView.addressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 500);
        }];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 160;
    }else{
        return 60;
    }
}

#pragma mark - 查询排行榜
- (void) getRankScoreInfo {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@/%@", [[VersionManager shareManager] currentVersion], kAllRank,[NSString stringWithFormat:@"result_type/%@/diff/%@", @"0", @"1"]];
    kDLog(@"查询排行榜的接口是：%@", getUrl);
    NSDictionary *geiDic = @{
                             @"user_id" : @"0000000002",
                             @"result_type" : @"0"
                             };
    
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        kDLog(@"查询排行榜接口返回的数据是：%@", result);
        [self.rankAry removeAllObjects];
        kDLog(@"查询排行榜接口返回的数据是：%@", result);
        if (result[@"data"] != [NSNull null]) {
            NSArray *ary = result[@"data"];
            if (ary.count > 0) {
                [self.rankAry addObjectsFromArray:ary];
            }
        }
        [self.leftView configWithRankAry:self.rankAry];
    } errorBlock:^(NSError *error) {
        
        kDLog(@"查询排行榜接口请求失败，错误是：%@", error);
    }];
}

#pragma mark - 查询个人成绩
- (void) getPersonalScoreInfo {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@/%@", [[VersionManager shareManager] currentVersion], kPersonalRank,[NSString stringWithFormat:@"user_id/%@/result_type/%@/diff/%@", @"0000000002", @"0", @"1"]];
    kDLog(@"查询个人成绩的接口是：%@", getUrl);
    
//    NSDictionary *geiDic = @{
//                             @"user_id" : @"0000000002",
//                             @"result_type" : @"0"
//                             };

    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        [self.resultsAry removeAllObjects];
        kDLog(@"查询个人成绩接口返回的数据是：%@", result);
        if (result[@"data"] != [NSNull null]) {
            NSArray *ary = result[@"data"];
            if (ary.count > 0) {
                [self.resultsAry addObjectsFromArray:ary];
            }
        }
        [self.leftView configWithPersonalData:self.resultsAry];
    } errorBlock:^(NSError *error) {
        
        kDLog(@"查询个人成绩接口请求失败，错误是：%@", error);
    }];
}



#pragma mark - 保存信息
- (void) didClickSendInfoButton:(NSDictionary *)infoDic {
    NSDictionary *userInfoDic = [NSDictionary dictionaryWithContentsOfFile:kInfoFilePath];
    
    NSDictionary *paramDic;
    
    if (self.addressAry.count != 0) {
        NSDictionary *proDic = self.addressAry[0];
        NSDictionary *cityDic = self.addressAry[1];
        NSDictionary *countyDic = self.addressAry[2];
        
        paramDic = @{
                     @"user_id":userInfoDic[@"user_id"],
                     @"nickname":infoDic[@"name"],
                     @"sign":infoDic[@"info"],
                     @"sex":@"1",
                     @"age":infoDic[@"age"],
                     @"provice_id":proDic[@"id"],
                     @"city_id":cityDic[@"id"],
                     @"district_id":countyDic[@"id"]
                     };
    } else {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:kInfoFilePath];
        paramDic = @{
                     @"user_id":userInfoDic[@"user_id"],
                     @"nickname":infoDic[@"name"],
                     @"sign":infoDic[@"info"],
                     @"sex":@"1",
                     @"age":infoDic[@"age"],
                     @"provice_id":dic[@"province_id"],
                     @"city_id":dic[@"city_id"],
                     @"district_id":dic[@"district_id"]
                     };
    }
    
    
    NSString *bookUrl = [NSString stringWithFormat:@"%@%@", [[VersionManager shareManager] currentVersion], kSETINFO];
    
    kDLog(@"修改用户信息的接口是：%@", bookUrl);
    kDLog(@"修改用户信息传的参数是：%@", paramDic);
    [CHNetWorkSingleton requestAFWithURL:bookUrl params:paramDic httpMethod:@"POST" isHUD:NO finishBlock:^(id result) {
        
        kDLog(@"修改用户信息接口返回的数据是：%@", result);
        if ([result[@"info"] isEqualToString:@"ok"]) {
            [self loadUserData];
        }
//        [dataArray removeAllObjects];
//
//        NSArray *bookArray = result[@"data"];
//
//        if ([result[@"code"] isEqualToString:@"11"]) {
//
//            for (NSDictionary *bookDic in bookArray) {
//
//                PTReadCheckModel *model = [PTReadCheckModel mj_objectWithKeyValues:bookDic];
//                [dataArray addObject:model];
//            }
//        }
//
//        //        [self.leftTab reloadData];
//        [self.classCollectionView reloadData];
//
//        kDLog(@"书籍是：%@", dataArray);
        
    } errorBlock:^(NSError *error) {
        
        kDLog(@"修改用户信息接口请求失败，错误是：%@", error);
    }];
    
    
}

#pragma mark - 更换头像
- (void)DidselectTHeadImg:(UIImageView *)headImg{
    NSLog(@"VC中更换头像");
    UIAlertController *popAlert = [UIAlertController alertControllerWithTitle:@"请选择" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *popAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *popAction2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
    }];
    [popAlert addAction:popAction];
    [popAlert addAction:popAction2];
    UIViewController *vc = [[UIApplication sharedApplication] keyWindow].rootViewController;
    [vc presentViewController:popAlert animated:YES completion:nil];
    
}
#pragma mark 从这里开始选择照片
#pragma mark 选择照片
- (void)pushTZImagePickerController {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:1 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.isStatusBarDefault = YES;
    imagePickerVc.allowCrop = NO;
//    imagePickerVc.cropRect = CGRectMake(0, 0, kScreenWidth, kScreenWidth);
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.infoView.headImg.image = photos[0];
        [self cheangeIcon:photos[0]];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - UIImagePickerController
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    NSLog(@"相机");
    [self openCamera];
}
- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //设置拍照后的图片可被编辑
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
    
}
#pragma mark - UIImagePickerController Delegate
///拍照、选视频图片、录像 后的回调（这种方式选择视频时，会自动压缩，但是很耗时间）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //媒体类型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //原图URL
    NSURL *imageAssetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    if ([mediaType isEqualToString:@"public.image"]) {
        
        UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
        //如果 picker 没有设置可编辑，那么image 为 nil
        if (image == nil) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        self.infoView.headImg.image = image;
        
        
        
        
        [self cheangeIcon:image];
        PHAsset *asset;
        //拍照没有原图 所以 imageAssetURL 为nil
        if (imageAssetURL) {
            PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[imageAssetURL] options:nil];
            asset = [result firstObject];
        }
        
    }
}
#pragma mark - 修改头像
- (void) cheangeIcon:(UIImage *)IconImg{
    
    
}

- (void) didSelectedAddress:(NSArray *)addressArray {
    
    NSLog(@"选择的地区信息是：%@", addressArray);
    self.addressAry = addressArray;
}

#pragma mark - 登陆
- (void)clickLogin {
    PTLoginVC *vc = [[PTLoginVC alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
}

- (NSMutableArray *)resultsAry {
    if (_resultsAry == nil) {
        _resultsAry = [NSMutableArray array];
    }
    return _resultsAry;
}

- (NSMutableArray *)rankAry {
    if (_rankAry == nil) {
        _rankAry = [NSMutableArray array];
    }
    return _rankAry;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
